package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.domain.CsmallAuthenticationInfo;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.order.mapper.OmsCartMapper;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.model.OmsCart;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

@DubboService
@Service
@Slf4j
public class OmsCartServiceImpl implements IOmsCartService {
    @Autowired
    private OmsCartMapper omsCartMapper;

    /**
     * 新增购物车商品
     * @param cartDTO 购物车新增数据
     */
    @Override
    public void addCart(CartAddDTO cartDTO) {
        //明确用户身份,获取用户ID
        Long userId = getUserId();
        //根据用户id和skuId检查当前用户购物车中是否存在该商品
        OmsCart omsCart = omsCartMapper.selectExistsCart(userId, cartDTO.getSkuId());
        if (omsCart == null) {
            //如果omsCart为null,表示当前用户没有添加这个商品,
            OmsCart newCart = new OmsCart();
            //将参数CartAddDTO对象的同名数赋值给newCart
            BeanUtils.copyProperties(cartDTO,newCart);
            newCart.setUserId(userId);

            int rows = omsCartMapper.saveCart(newCart);
            if(rows == 0){
                throw new CoolSharkServiceException(ResponseCode.CONFLICT,"购物车新增商品失败![1]");
            }
        }else {
            //如果omsCart不是null,表示当前用户之前将该sku添加到购物车中了
            //修改购物车中该sku数量
            omsCart.setQuantity(omsCart.getQuantity()+cartDTO.getQuantity());
            int rows = omsCartMapper.updateQuantityById(omsCart);
            if(rows == 0){
                throw new CoolSharkServiceException(ResponseCode.CONFLICT,"购物车新增商品失败![2]");
            }
        }

    }

    /**
     * 根据登录用户id分页查询购物车中商品信息
     * @param page  第几页
     * @param pageSize 每页条数
     * @return 购物车数据
     */
    @Override
    public JsonPage<CartStandardVO> listCarts(Integer page, Integer pageSize) {
        Long userId = getUserId();
        //PageHelper设置分页查询条件
        PageHelper.startPage(page,pageSize);
        //执行查询,会自动在sql语句末尾添加limit关键字完成分页
        List<CartStandardVO> list = omsCartMapper.selectCartsByUserId(userId);

        return JsonPage.restPage(new PageInfo<>(list));
    }

    @Override
    public void removeCart(Long[] ids) {
        int rows = omsCartMapper.deleteCartsByIds(ids);
        if(rows == 0){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"购物车中的商品已被删除!");
        }
    }

    @Override
    public void removeAllCarts() {
        Long userId = getUserId();
        int rows = omsCartMapper.deleteCartsByUserId(userId);
        if(rows == 0){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"购物车已经是空的了!");
        }
    }

    @Override
    public void removeUserCarts(OmsCart omsCart) {
        omsCartMapper.deleteCartByUserIdAndSkuId(omsCart);

    }

    @Override
    public void updateQuantity(CartUpdateDTO cartUpdateDTO) {
        OmsCart omsCart = new OmsCart();
        BeanUtils.copyProperties(cartUpdateDTO,omsCart);
        int rows = omsCartMapper.updateQuantityById(omsCart);
        if(rows == 0){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"商品修改失败!");
        }
    }

    public CsmallAuthenticationInfo getUserInfo(){
        // 编码获得SpringSecurity上下文中保存的权限
        UsernamePasswordAuthenticationToken  authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder
                        .getContext().getAuthentication();
        //判断获得的信息是不是null
        if (authenticationToken == null) {
            throw new CoolSharkServiceException(ResponseCode.UNAUTHORIZED,"请先登录!");
        }
        //上下文信息确定存在后,获取其中的用户信息
        CsmallAuthenticationInfo csmallAuthenticationInfo =
                (CsmallAuthenticationInfo) authenticationToken.getCredentials();
        return csmallAuthenticationInfo;

    }
    //获取用户的id的方法,
    public Long getUserId(){
        return getUserInfo().getId();
    }















    
}
















